// index.js
import product from "../js/product"
Page({

    data: {
        productList: [],
        lastItemId: "anchor",
        isShowCamera: false,
        lastCode: "",
        lastScanTime: 0,
        audioErr: null,
        audioOk: null
    },
    onLoad() {
        let err = wx.createInnerAudioContext();
        err.src = "/assets/audio/err.mp3"
        let ook = wx.createInnerAudioContext();
        ook.src = "/assets/audio/ok.mp3"
        this.setData({
            audioErr: err,
            audioOk: ook
        })
    },

    tijiao: function(params) {
        wx.showToast({
            title: '功能尚未开放',
            icon: 'error',
            duration: 1000
        })
    },

    scan: function(params) {
        let isShow = !this.data.isShowCamera;
        this.setData({
            isShowCamera: isShow
        })
    },

    scanRes: function(res) {
        let codeStr = res.detail.result
        if (this.data.lastCode == codeStr) {
            if ((new Date().getTime() - this.data.lastScanTime) / 1000 < 3) {
                return
            }
        }

        this.setData({ lastCode: codeStr, lastScanTime: new Date().getTime() })
        console.log(codeStr);

        let that = this

        let p = product.decode(codeStr)
        if (!p) {
            wx.showToast({
                title: '无法解析二维码',
                icon: 'error',
                duration: 1000
            })
            this.data.audioErr.play()
            return
        }

        let pl = that.data.productList

        if (pl.some(item => item.Skuno === p.Skuno)) {
            wx.showToast({
                title: '重复扫码',
                icon: 'error',
                duration: 1000
            })
            this.data.audioErr.play()
            return
        }
        pl.push(p)
        that.setData({
            productList: pl
        })
        this.data.audioOk.play()

        setTimeout(() => {
            console.log("111111111");
            that.setData({
                lastItemId: "item" + (pl.length - 1)
            })
        }, 150);

        wx.showToast({
            title: '扫码成功',
            icon: 'success',
            duration: 2000
        })

    }

})